import { NextApiRequest, NextApiResponse } from 'next';
import prisma from '../../../lib/prisma';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    if (req.method !== 'POST') {
        return res.status(405).json({ message: 'Method not allowed' });
    }

    const { userId, score } = req.body;

    if (!userId || typeof score !== 'number') {
        return res.status(400).json({ message: 'Invalid input' });
    }

    try {
        const user = await prisma.user.findUnique({
            where: { id:userId },
        });

        if (!user) {
            return res.status(404).json({ message: 'User not found' });
        }

        const updatedUser = await prisma.user.update({
            where: { id:userId },
            data: { score: user.score + score },
        });

        return res.status(200).json(updatedUser);
    } catch (error) {
        return res.status(500).json({ message: 'Internal server error', error });
    }
}